<template>
  <div class="add-contracts">
    <div class="header">
      <a-page-header title="批量生成合同" @back="goBack">
        <span>
          当您需要拟定多个配置相同的合同时，可以选择一个合同模板进行批量创建。请先对租客进行房源的绑定。
        </span>
      </a-page-header>
    </div>
    <div class="content">
      <a-card class="card">
        <a-row style="margin: 20px 0">
          <a-col :span="12" :offset="6">
            <a-steps :current="currentStep">
              <a-step title="选择合同模板" />
              <a-step title="确认合同信息" />
              <a-step title="完成" />
            </a-steps>
          </a-col>
        </a-row>
        <a-form style="margin-top: 40px">
          <a-row :gutter="[0, 12]">
            <template v-if="currentStep == 0">
              <a-col :span="8" :offset="8">
                <a-alert
                  show-icon
                  message="只会对合同模板应用范围下的租客进行生成"
                />
              </a-col>
              <a-col :span="8" :offset="8">
                <a-form-item label="合同模板">
                  <a-select
                    v-model:value="formState.template_id"
                    placeholder="请选择"
                    @select="handleTemplateSelect"
                  >
                    <a-select-option
                      v-for="item of templateList"
                      :key="item.id"
                    >
                      {{ item.template_name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="8">
                <a-form-item
                  label="选择楼宇"
                  :extra="formState.template_id ? '' : '请先选择合同模板'"
                >
                  <a-tree-select
                    v-model:value="buildCheckedKey"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择"
                    v-model:treeExpandedKeys="expandBuildKeys"
                    :tree-data="showVillageList"
                    @select="handleBuildSelect"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8" :offset="8">
                <a-form-item label="开始日期">
                  <a-date-picker
                    v-model:value="startDate"
                    placeholder="请选择合同开始日期"
                    style="width: 100%"
                    :valueFormat="DATE_FORMAT"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
            </template>
            <template v-if="currentStep == 1">
              <a-col :span="18" :offset="4">
                <a-row :gutter="[12, 12]">
                  <a-col :span="12">
                    <a-card
                      title="基本信息"
                      size="small"
                      :headStyle="cardHeadStyle"
                    >
                      <a-descriptions :column="1">
                        <a-descriptions-item label="签订日">
                          {{ contractInfo.sign_time }}
                        </a-descriptions-item>
                        <a-descriptions-item label="经办人">
                          {{ contractInfo.cuser_name }}
                        </a-descriptions-item>
                        <a-descriptions-item label="合同起止日期">
                          {{ contractInfo.lease_starttime }} ~
                          {{ contractInfo.lease_endtime }}
                        </a-descriptions-item>
                        <a-descriptions-item label="单位保留小数点">
                          {{ contractInfo.unit_price_point }}
                        </a-descriptions-item>
                        <a-descriptions-item label="计算精度">
                          {{ contractInfo.calculate_accuracy_txt }}
                        </a-descriptions-item>
                        <a-descriptions-item label="计算顺序">
                          {{ contractInfo.calculate_order_txt }}
                        </a-descriptions-item>
                        <a-descriptions-item label="应收整数">
                          {{ contractInfo.receivable_round_txt }}
                        </a-descriptions-item>
                      </a-descriptions>
                    </a-card>
                    <a-card
                      title="滞纳金"
                      size="small"
                      style="margin-top: 12px"
                      v-if="tplInfo.latefee_clause"
                      :headStyle="cardHeadStyle"
                    >
                      <a-descriptions :column="1">
                        <a-descriptions-item label="起算天数">
                          {{ tplInfo.latefee_clause.startDay || "--" }} 天
                        </a-descriptions-item>
                        <a-descriptions-item label="滞纳金比例">
                          {{ tplInfo.latefee_clause.ratio || "--" }} %/天
                        </a-descriptions-item>
                        <a-descriptions-item label="滞纳金上限">
                          {{ tplInfo.latefee_clause.toplimit || "--" }} %
                        </a-descriptions-item>
                      </a-descriptions>
                    </a-card>
                  </a-col>
                  <a-col :span="12">
                    <a-card
                      title="应用范围"
                      size="small"
                      :headStyle="cardHeadStyle"
                      style="height: 520px; overflow: auto"
                      v-if="relationRoomTree.length"
                    >
                      <a-tree
                        :tree-data="relationRoomTree"
                        :defaultExpandAll="true"
                        :blockNode="true"
                        :selectable="false"
                      >
                        <template #title="{ dataRef }">
                          <template v-if="dataRef.childType == 'room'">
                            <a-row
                              type="flex"
                              justify="space-between"
                              align="middle"
                            >
                              <a-col> {{ dataRef.title }} </a-col>
                              <a-col class="text-primary">
                                {{ dataRef.showArea }}㎡
                              </a-col>
                            </a-row>
                          </template>
                          <template v-else>
                            <span>{{ dataRef.title }}</span>
                          </template>
                        </template>
                      </a-tree>
                    </a-card>
                  </a-col>
                  <a-col :span="24">
                    <a-card
                      title="合同条款"
                      size="small"
                      :headStyle="cardHeadStyle"
                      v-if="tplInfo.multiple_clause"
                    >
                      <a-tabs v-model:activeKey="activePaneKey" type="card">
                        <a-tab-pane
                          v-for="clauseContent of tplInfo.multiple_clause"
                          :key="clauseContent.key"
                          :tab="clauseContent.name"
                          :closable="false"
                        >
                          <a-row
                            v-if="clauseContent.tempClauseInfo"
                            :gutter="[12, 12]"
                            class="pane-content"
                          >
                            <!-- 保证金 -->
                            <a-col
                              :span="12"
                              v-if="clauseContent.use_bond == 1"
                            >
                              <a-card
                                size="small"
                                title="保证金条款"
                                :headStyle="cardHeadStyle"
                                :bordered="false"
                              >
                                <a-descriptions :column="2">
                                  <a-descriptions-item label="保证金类型">
                                    {{
                                      getOptionsTxt(
                                        "bondType",
                                        clauseContent.tempClauseInfo.bond_clause
                                          .bond_type
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="保证金金额">
                                    {{
                                      (clauseContent.tempClauseInfo.bond_clause
                                        .bond_price || "--") +
                                      getOptionsTxt(
                                        "bond_unit",
                                        clauseContent.tempClauseInfo.bond_clause
                                          .bond_unit
                                      )
                                    }}
                                  </a-descriptions-item>
                                </a-descriptions>
                              </a-card>
                            </a-col>
                            <!-- 税率 -->
                            <a-col :span="12">
                              <a-card
                                size="small"
                                :title="clauseContent.cost_type_name + '含税'"
                                :headStyle="cardHeadStyle"
                                :bordered="false"
                              >
                                <a-descriptions :column="2">
                                  <a-descriptions-item label="含税规则">
                                    {{
                                      getOptionsTxt(
                                        "taxRule",
                                        clauseContent.tempClauseInfo.tax_clause
                                          .taxRule
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="税率" >
                                    {{clauseContent?.tempClauseInfo?.tax_clause?.taxRate || "--"}}
                                    %
                                  </a-descriptions-item>
                                </a-descriptions>
                              </a-card>
                            </a-col>
                            <!-- 租赁、物业条款 -->
                            <a-col
                              :span="24"
                              v-for="(clauseItem, index) of clauseContent
                                .tempClauseInfo.normalClause"
                              :key="'nc_' + index"
                            >
                              <a-card
                                size="small"
                                :title="
                                  clauseContent.cost_type_txt +
                                  (clauseContent.tempClauseInfo.normalClause
                                    .length > 1
                                    ? index + 1
                                    : '')
                                "
                                :headStyle="cardHeadStyle"
                                :bordered="false"
                              >
                                <a-descriptions :column="4">
                                  <a-descriptions-item label="单价">
                                    {{
                                      (clauseItem.contract_unit_price || "--") +
                                      getOptionsTxt(
                                        "contract_price_unit",
                                        clauseItem.contract_price_unit
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item
                                    label="天单价换算规则"
                                    v-if="
                                      !['unit_1', 'unit_4'].includes(
                                        clauseItem.contract_price_unit
                                      )
                                    "
                                  >
                                    {{
                                      getOptionsTxt(
                                        "convert_day_price",
                                        clauseItem.convert_day_price
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="付款时间">
                                    {{
                                      getOptionsTxt(
                                        "payment_time_unit1",
                                        clauseItem.payment_time_unit1
                                      ) +
                                      clauseItem.payment_time +
                                      getOptionsTxt(
                                        "payment_time_unit2",
                                        clauseItem.payment_time_unit2
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="计费类型">
                                    {{
                                      getOptionsTxt(
                                        "charge_type_unit",
                                        clauseItem.charge_type
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="年天数">
                                    {{ clauseItem.year_days }} 天
                                  </a-descriptions-item>
                                  <a-descriptions-item
                                    label="付款周期（几月一付）"
                                  >
                                    {{ clauseItem.payCycle || "--" }} 月
                                  </a-descriptions-item>
                                  <a-descriptions-item label="租期划分方式">
                                    {{
                                      getOptionsTxt(
                                        "lease_divide_unit",
                                        clauseItem.lease_divide
                                      )
                                    }}
                                  </a-descriptions-item>
                                </a-descriptions>
                              </a-card>
                            </a-col>
                            <!-- 优惠条款 -->
                            <a-col
                              :span="24"
                              v-for="(clauseItem, index) of clauseContent
                                .tempClauseInfo.discountClause"
                              :key="'dc_' + index"
                            >
                              <a-card
                                size="small"
                                :title="
                                  '优惠条款' +
                                  (clauseContent.tempClauseInfo.discountClause
                                    .length > 1
                                    ? index + 1
                                    : '')
                                "
                                :headStyle="cardHeadStyle"
                                :bordered="false"
                              >
                                <a-descriptions :column="4">
                                  <a-descriptions-item label="优惠类型">
                                    {{
                                      getOptionsTxt(
                                        "discount_type",
                                        clauseItem.discount_type
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item
                                    label="免租期划分方式"
                                    v-if="
                                      ['select_1', 'select_5'].includes(
                                        clauseItem.discount_type
                                      )
                                    "
                                  >
                                    {{
                                      getOptionsTxt(
                                        "exempt_lease_type",
                                        clauseItem.exempt_lease_type
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <template v-else>
                                    <a-descriptions-item label="开始期数">
                                      {{ clauseItem.stage_start }}
                                    </a-descriptions-item>
                                    <a-descriptions-item label="期长">
                                      {{ clauseItem.stage_num }}
                                    </a-descriptions-item>
                                    <a-descriptions-item
                                      :label="
                                        getOptionsTxt(
                                          'discount_type',
                                          clauseItem.discount_type
                                        )
                                      "
                                    >
                                      {{
                                        clauseItem.discount_num +
                                        (clauseItem.discount_type == "select_2"
                                          ? "折"
                                          : "元")
                                      }}
                                    </a-descriptions-item>
                                  </template>
                                </a-descriptions>
                              </a-card>
                            </a-col>
                            <!-- 递增条款 -->
                            <a-col
                              :span="24"
                              v-for="(clauseItem, index) of clauseContent
                                .tempClauseInfo.increaseClause"
                              :key="'ic_' + index"
                            >
                              <a-card
                                size="small"
                                :title="
                                  '递增条款' +
                                  (clauseContent.tempClauseInfo.increaseClause
                                    .length > 1
                                    ? index + 1
                                    : '')
                                "
                                :headStyle="cardHeadStyle"
                                :bordered="false"
                              >
                                <a-descriptions :column="4">
                                  <a-descriptions-item label="单价递增">
                                    {{
                                      clauseItem.incrPrice +
                                      getOptionsTxt(
                                        "price_increment_unit",
                                        clauseItem.incrPriceUnit
                                      )
                                    }}
                                  </a-descriptions-item>
                                  <a-descriptions-item label="保证金递增">
                                    {{
                                      clauseItem.incrBond +
                                      getOptionsTxt(
                                        "bond_increment_unit",
                                        clauseItem.incrBondUnit
                                      )
                                    }}
                                  </a-descriptions-item>
                                </a-descriptions>
                              </a-card>
                            </a-col>
                          </a-row>
                        </a-tab-pane>
                      </a-tabs>
                    </a-card>
                  </a-col>
                </a-row>
              </a-col>
            </template>
            <template v-if="currentStep == 2">
              <a-col :span="18" :offset="4">
                <a-result
                  status="success"
                  :title="
                    '本次操作共创建' + confirmedOwnerIds.length + '个合同'
                  "
                  sub-title="正在后台生成中，您可以关闭页面，完成后将通过站内信通知您"
                >
                  <template #extra>
                    <a-button @click="goBack"> 返回 </a-button>
                  </template>
                </a-result>
              </a-col>
            </template>
            <a-col :span="8" :offset="8" class="text-center">
              <a-space>
                <a-button
                  type="primary"
                  v-show="currentStep == 0"
                  :loading="nextStepLoading"
                  :disabled="nextStepDisabled"
                  @click="nextStepClick"
                >
                  下一步
                </a-button>
                <a-button v-show="currentStep == 1" @click="lastStepClick">
                  上一步
                </a-button>
                <a-button
                  type="primary"
                  v-show="currentStep == 1"
                  :loading="submitLoading"
                  @click="submitClick"
                >
                  提交
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 选择可跳过的租客 -->
    <a-modal
      v-model:visible="ownerVisible"
      centered
      :closable="false"
      :maskClosable="false"
      okText="继续"
      cancelText="取消"
      :width="880"
      @cancel="handleOwnerCancel"
      @ok="handleOwnerOk"
    >
      <template #title>
        <a-alert
          message="当前应用范围内有以下租客存在未归档的合同"
          type="warning"
          show-icon
        />
      </template>
      <div class="transfer-box">
        <span style="color: red"> 请选择仍需创建合同的租客 </span>
        <a-transfer
          style="margin-top: 10px"
          :data-source="unConfirmOwnerList"
          :list-style="{
            width: '360px',
            height: '500px',
          }"
          :operations="['加入右侧', '加入左侧']"
          :titles="['跳过创建合同的租客', '仍然创建合同']"
          :targetKeys="extraOwnerIds"
          @change="handleOwnerChange"
        >
          <template #render="item">
            <a-tooltip>
              <template #title>{{ getOwnerRoomInfo(item) }}</template>
              <span class="custom-item">
                {{ item.title }}
              </span>
            </a-tooltip>
          </template>
        </a-transfer>
      </div>
    </a-modal>

    <!-- loading (生成租金明细弹窗) -->
    <a-modal
      v-model:visible="loadingVisible"
      centered
      :closable="false"
      :maskClosable="false"
      :footer="null"
      title="正在批量生成合同"
    >
      <a-progress :percent="loadingPercent" />

      <a-alert
        show-icon
        type="warning"
        message="正在批量生成合同，请勿刷新或离开本页面！"
        style="margin-top: 20px"
      />
    </a-modal>
  </div>
</template>

<script>
import { message, Modal, Transfer, Result, Progress } from "ant-design-vue";
import {
  defineComponent,
  createVNode,
  reactive,
  toRefs,
  nextTick,
  computed,
  toRaw,
} from "vue";
import { useRouter } from "vue-router";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import moment from "moment";
import store from "../../../store";

const DATE_FORMAT = "YYYY-MM-DD";

export default defineComponent({
  name: "NewContracts",
  components: {
    "a-transfer": Transfer,
    "a-result": Result,
    "a-progress": Progress,
  },
  setup(props, { emit }) {
    const router = useRouter();

    const state = reactive({
      cardHeadStyle: { fontWeight: "bold" },
      // 当前步骤
      currentStep: 0,
      // 选择模板
      templateList: [],
      currentTemplate: {},
      // 模板下的项目和楼宇
      villageList: [],
      showVillageList: [],
      expandBuildKeys: [],
      buildCheckedKey: undefined,
      // 标识表单是否改值
      formStateChanged: true,
      // 下一步
      nextStepLoading: false,
      // 合同模板信息
      tplInfo: {},
      // 应用范围
      relationRoomTree: [],
      // 条款内容
      activePaneKey: "",
      // 初始化选项信息
      optionsInit: {},
      // 提交
      submitLoading: false,
      // 租客信息
      ownerVisible: false,
      ownerList: [],
      confirmedOwnerIds: [],
      unConfirmOwnerList: [],
      extraOwnerIds: [],
      // 生成合同
      loadingVisible: false,
      loadingPercent: 0,

      startDate: moment().format(DATE_FORMAT),
    });

    const formState = reactive({
      template_id: undefined,
      village_id: undefined,
      build_id: undefined,
    });

    const contractInfo = reactive({
      sign_time: moment().format(DATE_FORMAT),
      cuser_uid: 0,
      cuser_name: "",
      lease_starttime: "",
      lease_endtime: "",
      unit_price_point: 2,
      calculate_accuracy: "accuracy_1",
      calculate_order: "order_1",
      receivable_round: 1,
    });

    /** 下一步按钮是否可点击 */
    const nextStepDisabled = computed(
      () => !formState.template_id || !formState.build_id
    );

    /** 提交表单生成 */
    const submit = (params) => {
      console.log(" --- submit --- params", toRaw(params));
      state.submitLoading = false;
      request.post("/org", "/contract/batchCreate", params).then((res) => {
        state.loadingPercent = 100;
        setTimeout(() => {
          state.loadingVisible = false;
          state.currentStep++;
        }, 100);
      });
    };

    /** 获取租客所属房源信息 */
    const getOwnerRoomInfo = (current) => {
      const { build_bind } = current;
      const roomTxtArr = build_bind.room.map(
        (room) =>
          `${room.extra.village_name}/${room.extra.build_name}/${room.extra.layer_name}/${room.room_name}`
      );
      return roomTxtArr.join("、");
    };

    /** 批量生成合同 */
    const newContracts = () => {
      const ownerList = state.ownerList.filter((item) =>
        state.confirmedOwnerIds.includes(item.id)
      );
      console.log(" --- newContracts --- ownerList", toRaw(ownerList));
      if (!ownerList.length) {
        Modal.info({
          title: () => "提示",
          content: () => "所选房源没有（或已全部跳过）租客可以生成合同。",
          icon: () => createVNode(ExclamationCircleOutlined),
          centered: true,
        });
        state.submitLoading = false;
        return;
      }

      state.loadingVisible = true;
      state.loadingPercent = 0;
      const { latefee_clause, multiple_clause } = state.tplInfo;
      const params = {
        template_id: formState.template_id,
        late_fee: {
          startDay: latefee_clause.startDay,
          ratio: latefee_clause.ratio,
          toplimit: latefee_clause.toplimit,
        },
        main_info: contractInfo,
        owner_infos: [],
      };

      const totalCount = ownerList.length * multiple_clause.length + 1;
      let createCount = 0;
      for (let owner of ownerList) {
        let result = {
          owner_id: owner.id,
          build_bind: owner.build_bind,
          expense_clause: [],
        };
        for (let clause of multiple_clause) {
          getRentDetail(
            {
              checked_build: owner.build_bind,
              clause,
            },
            (res) => {
              result.expense_clause.push(res);
              createCount++;
              state.loadingPercent = parseInt((createCount / totalCount) * 100);
              if (createCount == totalCount - 1) {
                submit(params);
              }
            }
          );
        }
        params.owner_infos.push(result);
      }
    };
    /** 生成租金明细 */
    const getRentDetail = (info, callback) => {
      const { checked_build, clause } = info;
      const {
        tempClauseInfo: {
          tax_clause,
          bond_clause,
          normalClause,
          discountClause,
          increaseClause,
        },
      } = clause;
      let lease_area = 0;
      let checkedBuild = JSON.parse(JSON.stringify(checked_build));
      checkedBuild.room.forEach((room) => {
        let area =
          clause.attribute == "property" && room.charging_area
            ? Number(room.charging_area)
            : Number(room.rental_area);
        if (room.rent_area) {
          area =
            clause.attribute == "property" && room.charging_area
              ? area - Number(room.rent_area.property_square)
              : area - Number(room.rent_area.lease_square);
        }
        room.lease_area = area;
        lease_area += Number(area);
      });

      let current = {
        clause_id: clause.id,
        clause_type: clause.clause_type,
        attribute: clause.attribute,
        basic_clause: {
          lease_area,
          lease_square: "squareMetre",
          lease_mode: "",
        },
        bond_clause,
        tax_clause,
        remark_clause: "",
        checked_build: checkedBuild,
      };
      let params = {
        clause_id: clause.id,
        ...current.basic_clause,
        sign_time: contractInfo.sign_time,
        lease_starttime: contractInfo.lease_starttime,
        lease_endtime: contractInfo.lease_endtime,
        unit_price_point: contractInfo.unit_price_point,
        calculate_accuracy: contractInfo.calculate_accuracy,
        calculate_order: contractInfo.calculate_order,
        receivable_round: contractInfo.receivable_round,
        rentTaxTerms: tax_clause,
        bondTerms: bond_clause,
        leaseTerms: normalClause.map((item) => {
          item.compute_lease = "unit1";
          item.charge_begintime = contractInfo.lease_starttime;
          item.charge_endtime = contractInfo.lease_endtime;
          return item;
        }),
        incrTerms:
          increaseClause && increaseClause.length
            ? increaseClause.map((item) => {
                item.incrDate = contractInfo.lease_starttime;
                return item;
              })
            : [],
        discountTerms:
          discountClause && discountClause.length
            ? discountClause.map((item) => {
                item.discount_start_time = contractInfo.lease_starttime;
                item.discount_end_time = contractInfo.lease_endtime;
                return item;
              })
            : [],
      };
      current.multiple_clause = params.leaseTerms;
      current.discount_clause = params.discountTerms;
      current.increment_clause = params.incrTerms;
      console.log("-----------getRentDetail", params);
      request
        .post("/org", "/contract/reportPays", {
          baseTerm: JSON.stringify(params),
        })
        .then((res) => {
          current.report_detail = res.data;
          callback && callback(current);
        })
        .catch((err) => {
          message.error("合同批量生成中断，请重新提交生成！");
          state.submitLoading = false;
          state.loadingVisible = false;
        });
    };

    /** 选择不跳过的租客 */
    const handleOwnerChange = (nextTargetKeys) => {
      state.extraOwnerIds = nextTargetKeys;
    };

    /** 开启关闭租客选择弹窗 */
    const handleOwnerCancel = () => {
      state.submitLoading = false;
      state.ownerVisible = false;
    };
    const handleOwnerOk = () => {
      const extraIds = state.extraOwnerIds.map((id) => Number(id));
      state.confirmedOwnerIds = [...state.confirmedOwnerIds, ...extraIds];
      state.ownerVisible = false;
      newContracts();
    };

    /** 提交 */
    const submitClick = () => {
      if (state.unConfirmOwnerList.length) {
        // 有待确认的租客 弹窗确认
        state.ownerVisible = true;
        return;
      }
      state.submitLoading = true;
      if (state.confirmedOwnerIds.length) {
        // 没有待确认的租客 直接去生成合同
        newContracts();
      } else {
        // 没有获取数据
        getOwners();
      }
    };

    /**调取接口获取相关联的租客 */
    const getOwners = () => {
      state.confirmedOwnerIds = [];
      state.unConfirmOwnerList = [];
      request
        .get("/org", "/contract/templateMatchOwnerList", {
          ...formState,
        })
        .then((res) => {
          if (!res.goOwnerList.length && !res.passOwnerList.length) {
            // 没有查询到相关租客，没有批量要生成的合同,提示用户去租客页面关联房源
            Modal.warning({
              title: () => "提示",
              content: () =>
                "您所选楼宇下无任何房源绑定租客，请先前往租客管理页面去绑定租客与房源~",
              centered: true,
              onOk: () => {
                state.submitLoading = false;
              },
            });
          } else {
            state.ownerList = [...res.goOwnerList, ...res.passOwnerList];
            state.confirmedOwnerIds = res.goOwnerList.map((it) => it.id);
            state.unConfirmOwnerList = res.passOwnerList.map((it) => ({
              key: String(it.id),
              title: it.name,
              ...it,
            }));
            submitClick();
          }
        });
    };

    /** 整理合同基本信息 */
    const initContractBasicInfo = () => {
      // 信息回显
      contractInfo.lease_starttime = state.tplInfo.lease_starttime;
      const { basic_clause, multiple_clause } = state.tplInfo;
      store.dispatch("GetTemplateInit").then((initData) => {
        console.log("GetTemplateInit", initData);
        state.optionsInit = initData;
        contractInfo.lease_endtime = state.tplInfo.lease_endtime;
        contractInfo.unit_price_point = basic_clause.unit_price_point;
        const opt1 = initData.calculate_accuracy_unit.find(
          (item) => item.value == basic_clause.calculate_accuracy
        );
        contractInfo.calculate_accuracy = basic_clause.calculate_accuracy;
        contractInfo.calculate_accuracy_txt = opt1.label;
        const opt2 = initData.calculate_order_unit.find(
          (item) => item.value == basic_clause.calculate_order
        );
        contractInfo.calculate_order = basic_clause.calculate_order;
        contractInfo.calculate_order_txt = opt2.label;
        const opt3 = initData.receivable_round_unit.find(
          (item) => item.value == basic_clause.receivable_round
        );
        contractInfo.receivable_round = basic_clause.receivable_round;
        contractInfo.receivable_round_txt = opt3.label;
      });

      // 经办人
      contractInfo.cuser_uid = store.getters.userInfo.uid;
      contractInfo.cuser_name = store.getters.userInfo.realname;

      // 应用范围
      getRelationRoomTree();

      // 条款
      state.activePaneKey = multiple_clause[0].key;
    };
    // 获取应用范围
    const getRelationRoomTree = () => {
      const { relation_builds } = state.currentTemplate;
      state.relationRoomTree = [];
      const village = relation_builds.projectBuild.find(
        (item) => item.id == formState.village_id
      );
      const roomList = village.room.filter(
        (item) => item.build_id == formState.build_id
      );
      if (roomList.length) {
        const extraInfo = roomList[0].extra;
        const subTree = [];
        roomList.forEach((room) => {
          const { extra } = room;
          const layer = subTree.find((it) => it.id == extra.layer_id);
          //v3版本已弃用slots，使用会报错
          delete room.slots;
          room.childType = "room";
          if (layer) {
            layer.children.push(room);
          } else {
            subTree.push({
              key: `village_${extra.village_id}_build_${extra.build_id}_layer_${extra.layer_id}`,
              title: extra.layer_name,
              id: extra.layer_id,
              childType: "layer",
              children: [room],
            });
          }
        });

        state.relationRoomTree = [
          {
            key: `village_${village.id}`,
            title: extraInfo.village_name,
            id: village.id,
            short_name: extraInfo.village_short_name,
            childType: "village",
            children: [
              {
                key: `village_${village.id}_build_${extraInfo.build_id}`,
                title: extraInfo.build_name,
                id: extraInfo.build_id,
                build_number: extraInfo.build_number,
                childType: "build",
                children: subTree,
              },
            ],
          },
        ];
      }

      console.log("state.relationRoomTree", state.relationRoomTree);
    };

    /** 获取合同模板详情 */
    const getContractTplInfo = (callback) => {
      request
        .get("/org", "/contract/clauseTemplate/detail", {
          id: formState.template_id,
          start_time: state.startDate,
        })
        .then((res) => {
          if (validateTplDetail(res.data)) {
            state.tplInfo = res.data;
            callback && callback();
          } else {
            // 验证选择的合同模板是否所有填写项都填写了
            Modal.confirm({
              title: () => "提示",
              content: () =>
                "所选合同模板需要填写合同所有信息以生成租金明细，请完善您选择的合同模板！",
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "去完善",
              onOk() {
                router.push({
                  name: "newContractTemplate",
                  query: {
                    id: formState.template_id,
                  },
                });
              },
              onCancel() {
                goBack();
              },
            });
          }
        });
    };

    const validateTplDetail = (detail) => {
      const { basic_clause, multiple_clause } = detail;
      // 合同生效时间
      if (!basic_clause.validTime || !basic_clause.validTime.num) {
        return false;
      }
      for (let clause of multiple_clause) {
        const {
          tempClauseInfo: {
            tax_clause,
            bond_clause,
            normalClause,
            discountClause,
            increaseClause,
          },
        } = clause;
        // 税率
        if (tax_clause.taxRule == 1 && !tax_clause.taxRate) {
          return false;
        }
        // 保证金
        if (!bond_clause.bond_price) {
          bond_clause.bond_price = 0;
        }
        // 租赁条款
        for (let nc of normalClause) {
          // !合同单价 || !付款时间 || !付款周期
          if (
            (!nc.contract_unit_price && nc.contract_unit_price != 0) ||
            (!nc.payment_time && nc.payment_time != 0) ||
            !nc.payCycle
          ) {
            return false;
          }
        }
        // 优惠条款
        if (discountClause && discountClause.length) {
          for (let dc of discountClause) {
            const { discount_type } = dc;
            if (
              discount_type != "select_1" &&
              discount_type != "select_5" &&
              (!dc.stage_start || !dc.stage_num || !dc.discount_num)
            ) {
              return false;
            }
          }
        }
        // 递增条款
        if (increaseClause && increaseClause.length) {
          for (let dc of increaseClause) {
            if (!!dc.incrPrice) {
              dc.incrPrice = 0;
            }
            if (!dc.incrBond) {
              return false;
            }
          }
        }
      }
      return true;
    };

    /** 下一步 */
    const nextStepClick = () => {
      state.nextStepLoading = true;
      getContractTplInfo(() => {
        state.formStateChanged = false;
        state.nextStepLoading = false;
        state.currentStep++;
        initContractBasicInfo();
      });
      // 重置租客信息
      state.ownerList = [];
      state.confirmedOwnerIds = [];
      state.unConfirmOwnerList = [];
    };

    /** 上一步 */
    const lastStepClick = () => {
      state.currentStep--;
    };

    /** options key=>value */
    const getOptionsTxt = (optionKey, value) => {
      if (!state.optionsInit[optionKey] || !value) {
        return "";
      }
      const result = state.optionsInit[optionKey].find(
        (item) => item.value == value
      );
      return result.label;
    };

    /** 选择楼宇 */
    const handleBuildSelect = (val, node) => {
      formState.village_id = node.village_id;
      formState.build_id = node.id;
      state.formStateChanged = true;
    };

    /** 获取可选楼宇 */
    const getBuildingList = () => {
      getVillageList().then(() => {
        const { relation_builds } = state.currentTemplate;
        let expandBuildKeys = [];
        state.showVillageList = relation_builds.projectBuild.map((item) => {
          const villageItem = state.villageList.find((v) => v.id == item.id);
          const buildList = villageItem.buildList.filter((it) =>
            item.build.includes(it.id)
          );
          let newItem = {
            ...villageItem,
            key: `village_${villageItem.id}`,
            value: `village_${villageItem.id}`,
            title: villageItem.name,
            selectable: false,
            children: buildList.map((build) => ({
              ...build,
              key: `build_${build.id}`,
              value: `build_${build.id}`,
              title: build.build_name,
            })),
          };
          expandBuildKeys.push(newItem.key);
          return newItem;
        });
        nextTick(() => {
          state.expandBuildKeys = [...expandBuildKeys];
        });
      });
    };
    const getVillageList = () => {
      return new Promise((resolve) => {
        if (state.villageList.length) {
          resolve();
        } else {
          request
            .get("/org", "/build/villageAndBuildList/v2", {
              checked: 0,
              attach_department: 0,
            })
            .then((res) => {
              state.villageList = res.villageList;
              resolve();
            });
        }
      });
    };

    /** 选择模板 */
    const handleTemplateSelect = (val) => {
      if (state.currentTemplate.id && val == state.currentTemplate.id) {
        return;
      }
      state.currentTemplate = state.templateList.find((item) => item.id == val);
      formState.village_id = undefined;
      formState.build_id = undefined;
      state.formStateChanged = true;
      getBuildingList();
    };

    /** 获取自定义模板 */
    const getTemplate = () => {
      request
        .get("/org", "/contract/beforeCreateVerify")
        .then((res) => {
          if (res.list.length) {
            state.templateList = res.list;
          } else {
            Modal.confirm({
              title: () => "提示",
              content: () => "当前未配置自定义合同模板",
              icon: () => createVNode(ExclamationCircleOutlined),
              centered: true,
              okText: () => "前往配置",
              onOk() {
                router.push({
                  name: "contractTemplateList",
                });
              },
              onCancel() {
                goBack();
              },
            });
          }
        })
        .catch(() => {
          goBack();
        });
    };

    /** 返回 */
    const goBack = () => {
      if (window.history.state.back) {
        router.back();
      } else {
        router.replace({
          name: "contractList",
        });
      }
    };

    /** 初始化 */
    const init = () => {
      getTemplate();
    };
    init();

    return {
      formState,
      contractInfo,
      nextStepDisabled,
      ...toRefs(state),
      goBack,
      nextStepClick,
      lastStepClick,
      submitClick,
      handleTemplateSelect,
      handleBuildSelect,
      getOptionsTxt,
      handleOwnerChange,
      handleOwnerCancel,
      handleOwnerOk,
      getOwnerRoomInfo,
      DATE_FORMAT,
    };
  },
});
</script>

<style lang="less" scoped>
.add-contracts {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .header {
    background: #fff;
  }
  .content {
    flex: 1;
    padding: 10px;
    overflow: hidden auto;
    .card {
      min-height: 100%;
    }
  }
}
.pane-content {
  :deep(.ant-card) {
    background: #f7f7f7;
  }
  :deep(.ant-card-head) {
    border-bottom: 1px solid #dedede;
  }
}
</style>
